﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Entitys.Common.Dto.Event;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Interfaces.Common;
using SHZY.Business.Entity.Common;
using SHZY.Business.Interfaces.Common;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.BaseData.Common
{
    /// <summary>
    /// 业务实现：打印事件与打印配置关联.
    /// </summary>
    [ApiDescriptionSettings(Tag = "system", Name = "ComBaseEvent", Order = 200)]
    [Route("api/Common/BaseData/[controller]")]
    public class ComBaseEventService : IComBaseEventService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<ComBaseEventEntity> _repository;

        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ComBaseEventService"/>类型的新实例.
        /// </summary>
        public ComBaseEventService(
        ISqlSugarRepository<ComBaseEventEntity> comBaseEventRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
        {
            _repository = comBaseEventRepository;
            _dataInterfaceService = dataInterfaceService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取打印事件与打印配置关联.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBaseEventInfoOutput>();
        }

        /// <summary>
        /// 获取打印事件与打印配置关联列表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ComBaseEventListQueryInput input)
        {
            var data = await _repository.Context.Queryable<ComBaseEventEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.eventCode), it => it.EventCode.Contains(input.eventCode))
                .WhereIF(!string.IsNullOrEmpty(input.printConfigId), it => it.PrintConfigId.Equals(input.printConfigId))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.EventCode.Contains(input.keyword) || it.PrintConfigId.Contains(input.keyword))
                .Where(it => it.DeleteMark == null)
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.CreatorTime,OrderByType.Desc)
                .Select(it => new ComBaseEventListOutput
                {
                    id = it.Id,
                    eventCode = it.EventCode,
                    enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
                    //printConfigId = it.PrintConfigId,
                    printConfigId = SqlFunc.Subqueryable<ComBasePrintConfigEntity>().Where(p => p.Id == it.PrintConfigId).Select(p => p.Name)
                }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<ComBaseEventListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建打印事件与打印配置关联.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ComBaseEventCrInput input)
        {
            if (await _repository.AnyAsync(x => x.EventCode == input.eventCode&&x.PrintConfigId==input.printConfigId && x.DeleteMark == null))
                throw Oops.Oh(ErrorCode.COM1004);
            var entity = input.Adapt<ComBaseEventEntity>();
            //entity.Id = SnowflakeIdHelper.NextId();
            var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 更新打印事件与打印配置关联.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ComBaseEventUpInput input)
        {
            if (await _repository.AnyAsync(x => x.EventCode == input.eventCode && x.PrintConfigId == input.printConfigId && x.DeleteMark == null && x.Id != input.id))
                throw Oops.Oh(ErrorCode.COM1004);
            var entity = input.Adapt<ComBaseEventEntity>();
            var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
            {
                it.EventCode,
                it.PrintConfigId,
                it.EnabledMark,
            }).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除打印事件与打印配置关联.
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var isOk = await _repository.Context.Updateable<ComBaseEventEntity>().SetColumns(it => new ComBaseEventEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(it => it.Id.Equals(id)).ExecuteCommandHasChangeAsync();
            if (!isOk) throw Oops.Oh(ErrorCode.COM1002);
        }
    }
}
